import axios from 'axios'
import store from '../store/store'
import router from '../router/index'
import {getCookie,delCookie} from "./utils";
// axios 配置
axios.defaults.timeout = 15000;
axios.defaults.baseURL = process.env.BASE_URL;
// axios.defaults.headers.post['content-Type'] = 'application/x-www-form-urlencoded';

// http request 拦截器
axios.interceptors.request.use(
    config => {
        // console.log(config)
        const userInfo = JSON.parse(getCookie('userInfo'));
        if (store.state.userData.sessionId || userInfo) {
            config.headers.common['token'] = userInfo ? userInfo.sessionId : store.state.userData.sessionId;
        }
        store.commit('updateLoadingStatus', true);
        return config;
    },
    err => {
        store.commit('updateLoadingStatus', false);
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        if(response.data.code ==401 || response.data.code == -1){
            delCookie('userInfo');
            router.replace({
                path: '/login'
            })
        }
        store.commit('updateLoadingStatus', false);
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                    store.commit('clearUserData');
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }else {
            //alert('网络异常!');
        }
        store.commit('updateLoadingStatus', false);
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response.data)
    });

export default axios;
